package cn.acac.yygh.hosp.controller.admin;

import cn.acac.yygh.exception.MyException;
import cn.acac.yygh.hosp.service.HospitalSetService;
import cn.acac.yygh.model.hosp.HospitalSet;
import cn.acac.yygh.result.R;
import cn.acac.yygh.utils.MD5;
import cn.acac.yygh.vo.hosp.HospitalSetQueryVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.Update;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Random;

@RestController
@RequestMapping("/admin/hospitalSet")
@Api(tags = "这是医院的基本操作")
public class HospitalSetController {

    @Autowired
    private HospitalSetService hospitalSetService;

    /**
     * 批量删除医院信息
     * @param ids
     * @return
     */
    @ApiOperation(value = "根据多个id进行批量删除")
    @DeleteMapping("/deleteBatchIds")
    public R deleteBatchIds(@RequestBody List<Long> ids){
        hospitalSetService.removeByIds(ids);
        return R.ok();
    }

    /**
     * 更改医院的锁定与解锁
     * @param id
     * @param status
     * @return
     */
    @ApiOperation(value = "更改医院的锁定与解锁")
    @PutMapping("/lockUpdateHospSet/{id}/{status}")
    public R lockUpdateHospSet(@PathVariable("id")Long id,
                               @PathVariable("status")Integer status){
        // 新建一个医院对象
        HospitalSet hospitalSet = new HospitalSet();
        hospitalSet.setId(id);
        hospitalSet.setStatus(status);
        // 根据id进行更新
        hospitalSetService.updateById(hospitalSet);
        return R.ok();
    }


    /**
     * 根据id查询医院信息
     * @param id
     * @return
     */
    @ApiOperation(value = "根据医院的id查询医院信息")
    @GetMapping("/findHospSetById/{id}")
    public R findHospSetById(@PathVariable("id")Long id){
        // 调用方法进行查询
        return R.ok().setData("item",hospitalSetService.getById(id));
    }

    /**
     * 根据医院id修改医院信息
     * @param hospitalSet
     * @return
     */
    @ApiOperation(value = "根据医院id修改医院信息")
    @PutMapping("/updateHospSet")
    public R updateHospSetById(@RequestBody HospitalSet hospitalSet){
        // 根据id进行修改
        try {
            hospitalSetService.updateById(hospitalSet);
        } catch (RuntimeException e) {
            throw new MyException(5000,"此编码已存在！");
        }
        return R.ok();
    }


    /**
     * 添加医院的信息
     * @param hospitalSet
     * @return
     */
    @ApiOperation(value = "保存医院的信息")
    @PostMapping("/saveHospSet")
    public R saveHospital(@RequestBody HospitalSet hospitalSet){
        // 给新增的医院添加状态和秘钥
        hospitalSet.setStatus(1);   // 1为正常，0为不正常
        // 使用MD5对秘钥进行加密
        Random random = new Random();
        String encrypt = MD5.encrypt(System.currentTimeMillis() + "" + random.nextInt(1000));
        hospitalSet.setSignKey(encrypt);
        hospitalSetService.save(hospitalSet);
        return R.ok();
    }

    /**
     * 带条件的查询方法
     * @param pageNum   当前页
     * @param pageSize  每页显示多少条数据
     * @param hospitalSetQueryVo    查询条件的参数
     * @return
     */
    @ApiOperation(value = "这是分页带条件的查询")
    @PostMapping("/findAll/{pageNum}/{pageSize}")
    public R findAllPage(@PathVariable("pageNum")Integer pageNum,
                         @PathVariable("pageSize")Integer pageSize,
                         @RequestBody HospitalSetQueryVo hospitalSetQueryVo){
        // 创建分页对象,并将参数传递进去
        Page<HospitalSet> page = new Page<>(pageNum,pageSize);
        // 创建分页条件
        QueryWrapper<HospitalSet> queryWrapper = new QueryWrapper<>();
        // 判断是否为空
        if(!StringUtils.isEmpty(hospitalSetQueryVo.getHosname()) &&
                !StringUtils.isEmpty(hospitalSetQueryVo.getHoscode())){
            // 医院名称进行模糊查询,对医院编号进行精确查询
            queryWrapper.like("hosname",hospitalSetQueryVo.getHosname());
            queryWrapper.eq("hoscode",hospitalSetQueryVo.getHoscode());
        }else if(!StringUtils.isEmpty(hospitalSetQueryVo.getHoscode())) {
            // 医院编号进行精确查询
            queryWrapper.eq("hoscode", hospitalSetQueryVo.getHoscode());
        }else if(!StringUtils.isEmpty(hospitalSetQueryVo.getHosname())){
            // 医院名称进行模糊查询
            queryWrapper.like("hosname",hospitalSetQueryVo.getHosname());
        }
        hospitalSetService.page(page,queryWrapper);
        // 将查询结构返回
        return R.ok().setData("total",page.getTotal()).setData("rows",page.getRecords());
    }

    //查询所有医院信息
    @GetMapping("/findAll")
    @ApiOperation(value = "这是获取所有医院的信息")
    public R findAll() {
        // 编写一个异常
        // int a = 10 / 0;
        // int[] arr = new int[5];
        // System.out.println("arr[6] = " + arr[5]); // 数组角标越界异常，测试全局异常处理
        if(1 == 1){
            throw new MyException(5001,"这是测试自定义异常，可以忽略！");
        }
        List<HospitalSet> list = hospitalSetService.list();
        return R.ok().setData("list",list);
    }

    /**
     * 根据医院id删除医院信息（逻辑删除）
     * @param id    要删除的医院id
     * @return
     */
    @DeleteMapping("/delete/{id}")
    @ApiOperation(value = "根据医院id删除医院信息")
    public R deleteById(@ApiParam("需要删除的id") @PathVariable("id")Long id){
        // 进行删除操作
//        try {
//            Thread.sleep(2000);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
        hospitalSetService.removeById(id);
        return R.ok().message("删除成功！");
    }


}
